package com.hlf.common.utils;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

//AES加密解密
public class CipherAES {
    private  static final String tag = "CipherAES";
    private  String charset = "UTF-8";
    private SecretKey sk;
    private int mode;
    /**
     * AES加密解密算法
     */
    private  String algorithm = "AES";
    /**
     * AES 秘钥
     */
    private String key;

    /**
     * 初始化AES 上下文
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     */
    public void init(int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
        byte[] keybyte = getKeyByStr(key);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(keybyte);
        KeyGenerator keygen = KeyGenerator.getInstance(algorithm);
        keygen.init(secureRandom);
        sk = keygen.generateKey();
        this.mode = mode;
    }

    /**
     * @param src 加密前数据字节
     * @return
     * @description: AES加密实现
     */
    public byte[] encryptMode(byte[] src) {
        try {
            Cipher cip = Cipher.getInstance(algorithm);
            cip.init(Cipher.ENCRYPT_MODE, sk);
            return cip.doFinal(src);
        } catch (Exception e3) {
            System.out.println("加密异常:"+e3.getMessage());
        }
        return null;
    }

    /**
     * @param content 加密前数据
     * @return
     * @description: AES加密算法入口
     */
    public    String encrypt4Aes(String content) {
        try {
            byte[] src = content.getBytes(charset);
            //加密
            byte[] bytOut = encryptMode(src);
            return base64encode(bytOut);
        } catch (Exception e3) {
            e3.printStackTrace();
            System.out.println("加密异常:"+e3.getMessage());
        }
        return null;

    }


    public  byte[] decryptMode( byte[] src) {
        try {
            Cipher cip = Cipher.getInstance(algorithm);
            cip.init(Cipher.DECRYPT_MODE, sk);
            return cip.doFinal(src);
        } catch (Exception e3) {
            System.out.println("解密异常:"+e3.getMessage());
        }
        return null;
    }

    public byte[] decrypt4Aes(String contentbase64) {
        try {
            byte[] src = base64decode(contentbase64);
            //解密
            return decryptMode( src);
        } catch (Exception e3) {
            System.out.println("解密异常:"+e3.getMessage());
        }
        return null;

    }

    /**
     * AES算法解密入口
     */
    public String decrypt4Aes2Str(String contentbase64) {
        String Result = null;
        try {
            byte[] dst = decrypt4Aes(contentbase64);
            if (null != dst) {
                Result = new String(dst, charset);
            }
        } catch (Exception e3) {
            System.out.println("解密异常:"+e3.getMessage());
        }
        return Result;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";

        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) hs = hs + "0" + stmp;
            else hs = hs + stmp;
            if (n < b.length - 1) hs = hs + ",";
        }
        return hs.toUpperCase();
    }

    public static byte[] getKeyByStr(String str) {
        byte[] bRet = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            Integer itg = new Integer(16 * getChrInt(str.charAt(2 * i)) + getChrInt(str.charAt(2 * i + 1)));
            bRet[i] = itg.byteValue();
        }
        return bRet;
    }

    public static int getChrInt(char chr) {
        int iRet = 0;
        if (chr == "0".charAt(0)) iRet = 0;
        if (chr == "1".charAt(0)) iRet = 1;
        if (chr == "2".charAt(0)) iRet = 2;
        if (chr == "3".charAt(0)) iRet = 3;
        if (chr == "4".charAt(0)) iRet = 4;
        if (chr == "5".charAt(0)) iRet = 5;
        if (chr == "6".charAt(0)) iRet = 6;
        if (chr == "7".charAt(0)) iRet = 7;
        if (chr == "8".charAt(0)) iRet = 8;
        if (chr == "9".charAt(0)) iRet = 9;
        if (chr == "A".charAt(0)) iRet = 10;
        if (chr == "B".charAt(0)) iRet = 11;
        if (chr == "C".charAt(0)) iRet = 12;
        if (chr == "D".charAt(0)) iRet = 13;
        if (chr == "E".charAt(0)) iRet = 14;
        if (chr == "F".charAt(0)) iRet = 15;
        return iRet;

    }

    public static String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();
    }

    //  将 s 进行 BASE64 编码
    public static String strBase64encode(String str) {
        byte[] src = str.getBytes();
        return base64encode(src);
    }

    //  将 s 进行 BASE64 编码
    public static String base64encode(byte[] src) {
        if (src == null) return null;
        return (new sun.misc.BASE64Encoder()).encode(src);
    }

    //将 BASE64 编码的字符串 s 进行解码
    public static byte[] base64decode(String s) {
        if (s == null) return null;

        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return b;
        } catch (Exception e) {
            return null;
        }
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public static void main(String[] args) {
        CipherAES cipherAES = new CipherAES();
        cipherAES.setKey("DF94CBDCA294DC5DEF1368E64313FD3B98FE5EBCAB7F23AE");
        try {
            cipherAES.init(Cipher.DECRYPT_MODE);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        String beforeStr = "6362291234567894";
        System.out.println("加密前卡号：" + beforeStr);

        String encrypt3des = cipherAES.encrypt4Aes(beforeStr);
        System.out.println("加密后卡号：" + encrypt3des);

        System.out.println("解密后卡号：" + cipherAES.decrypt4Aes2Str(encrypt3des));
}}

